
const app = getApp()

Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    canIUseGetUserProfile: false,
    canIUseOpenData: false, // 如需尝试获取用户信息可改为false
    pops:false,
    saveStatus:false,
    list:[
      // {
      //   donate_title:'龙江镇困难精神病人医疗救助龙江镇困难精神病人医疗救助',
      //   time:'2020年9月1日',
      //   money:'1.00',
      //   name:"用户"
      // },
      // {
      //   donate_title:'龙江镇困难精神病人医疗救助',
      //   time:'2020年9月1日',
      //   money:'1.00',
      //   name:"用户"
      // },
      // {
      //   donate_title:'龙江镇困难精神病人医疗救助',
      //   time:'2020年9月1日',
      //   money:'1.00',
      //   name:"用户"
      // }
    ]
   // canIUseOpenData: wx.canIUse('open-data.type.userAvatarUrl') && wx.canIUse('open-data.type.userNickName') // 如需尝试获取用户信息可改为false
  },
  // 事件处理函数
  bindViewTap() {
    wx.navigateTo({
      // url: '../logs/logs'
    })
  },
  onLoad() {
    var that = this;
    var openid = wx.getStorageSync("openid");
    var userInfo = wx.getStorageSync("userInfo");
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }
    if (openid!='' ) {
      this.setData({
        hasUserInfo: true,
        userInfo: userInfo
      })

      wx.request({
        url: app.globalData.baseUrl + '/api/index/myPayRecord',
        data:{
          'openid':openid
        },
        header: {
          'content-type': 'application/json'
        },
        success: res => {
          console.log(res.data)
          this.setData({
            list: res.data.data
          })
        }
      })


    };
  },
  toSave:function(e){
    var self = this;
    console.log(e);
    self.saveImg(e.currentTarget.dataset.name,e.currentTarget.dataset.donate_title,e.currentTarget.dataset.time,e.currentTarget.dataset.money)
  },

  saveImg:function(name1,title1,time,money){
    wx.showLoading({
      title: '合成海报中',
    })
    var that  = this;
    that.setData({
      saveStatus:true
    })
    var userInfo = that.data.userInfo;
    var context = wx.createCanvasContext('mycanvas',that);
    context.setFillStyle("#ffe200")
    context.fillRect(0, 0, 640, 945)
    var path1 = userInfo.avatarUrl;
    var path2 = "https://donate.kyhdmedia.com/static/uploads/app/post1.png";
    var path3 = "https://donate.kyhdmedia.com/static/uploads/app/er.png";
    let promise1 = new Promise(function(resolve, reject) {
      wx.getImageInfo({
        src: path1,
        success: function(res) {
          resolve(res.path);
        }
      })
    });
    let promise2 = new Promise(function(resolve, reject) {
      wx.getImageInfo({
        src: path2,
        success: function(res) {
          resolve(res.path);
        }
      })
    });
    let promise3 = new Promise(function(resolve, reject) {
      wx.getImageInfo({
        src: path3,
        success: function(res) {
          resolve(res.path);
        }
      })
    });
    
    Promise.all([promise1,promise2,promise3]).then(res=>{
      context.drawImage(res[0], 265,304, 114, 114);
      context.drawImage(res[1], 0, 0, 640, 945);
      context.drawImage(res[2], 50, 722, 136, 134);
      var name = '亲爱的'+name1;
      var l = 0;
      var title = "";
      for(var i=0; i<name.length; i++)
      {
        var reg=/^[\u4E00-\u9FA5]+$/;
        var reg1 = /[\u3002|\uff1f|\uff01|\uff0c|\u3001|\uff1b|\uff1a|\u201c|\u201d|\u2018|\u2019|\uff08|\uff09|\u300a|\u300b|\u3008|\u3009|\u3010|\u3011|\u300e|\u300f|\u300c|\u300d|\ufe43|\ufe44|\u3014|\u3015|\u2026|\u2014|\uff5e|\ufe4f|\uffe5]/;
        if(reg.test(name[i])||reg1.test(name[i]))
        {
          l+=2;
        }else{
          l+=1;
        }
        if(l>40)
        {
          title = name.substring(0,i-1)+'...';
          break;
        }
      }
      if(l<=40){
        title = name;
      }
      context.setFillStyle('#4d2600');
      context.setFontSize(24);
      context.fillText(title,70, 480);
      
      // context.
      context.setTextAlign('left');  
      var l = 0;
      var j = 0;
      var k = 0;
      var lg = [36,42,42,42,42];
      var txt = [];
      var yes = false;
      var word = '感谢您于'+time+'向佛山市顺德区龙江慈善会的'+title1+'捐款￥'+money+'元。我们将遵照您的意愿，全部用于公益慈善事业。对于您的善行义举，致以诚挚的敬意。';
      for(var i=0; i<word.length; i++)
      {
        var reg=/^[\u4E00-\u9FA5]+$/;
        var reg1 = /[\u3002|\uff1f|\uff01|\uff0c|\u3001|\uff1b|\uff1a|\u201c|\u201d|\u2018|\u2019|\uff08|\uff09|\u300a|\u300b|\u3008|\u3009|\u3010|\u3011|\u300e|\u300f|\u300c|\u300d|\ufe43|\ufe44|\u3014|\u3015|\u2026|\u2014|\uff5e|\ufe4f|\uffe5]/;
        var add = 0;
        if(reg.test(word[i])||reg1.test(word[i]))
        {
          add=2;
        }else{
          add=1;
        }
        l+=add;
        if(l==lg[k])
        {
          txt.push(word.substring(j,i+1));
          console.log(i);
          j = i+1;
          l = 0;
          k++;
          yes = true;
        }else if(l>lg[k])
        {
          txt.push(word.substring(j,i));
          j = i;
          l = add;	
          yes = true;
          k++;
        }else if(i==word.length-1)
        {
          if(l<lg[k])
          {
            k++;
            txt.push(word.substring(j,word.length));
          }
        }
      }
      console.log(txt);  
      var xx  = [120,70,70,70,70];
      var yy  = [530,575,620,665,710];
      for(var i=0; i<txt.length; i++)
      {
        context.fillText(txt[i],xx[i], yy[i],508);
      }
      context.setTextAlign('left');  
      var company = '佛山市顺德区龙江慈善会';
      context.fillText(company,574-context.measureText(company).width,774);
      context.fillText(time,574-context.measureText(time).width,816);
      context.draw();
      setTimeout(function () {
        wx.canvasToTempFilePath({
          canvasId: 'mycanvas',
          fileType: 'png',
          destWidth: 640,
          destHeight: 945,
          success: function (res) {
            var tempFilePath = res.tempFilePath;
            console.log(tempFilePath);
            wx.hideLoading();
            that.setData({
              imagePath: tempFilePath,
              pops:true,
              saveStatus:false
            });
          },
          fail: function (res) {
            console.log(res);
          }
        })  
      }, 2000);
    })
  },
  confrimPop:function(){
    this.setData({
      pops:false
    });
  },
  getUserProfile(e) {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '展示用户信息',
      success: (res) => {
        console.log(res)
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
        wx.setStorageSync("userInfo", res.userInfo);
        var rawData = res.rawData;
        var signature = res.signature;
        var encryptData = res.encryptData;
       // var encryptedData = encodeURIComponent(res.encryptedData);
        var encryptedData = res.encryptedData;
        var iv = res.iv;
        wx.setStorageSync("iv", iv);
        wx.setStorageSync("encryptedData", encryptedData);
        wx.login({
          success: res => {
            // 发送 res.code 到后台换取 openId, sessionKey, unionId
            console.log(res.code);
            wx.request({
              url: app.globalData.baseUrl  + '/api/index/jscode2session',
              data: {
                code: res.code,
              },
              header: {
                "Content-Type": "application/x-www-form-urlencoded" // 默认值
              },
              method: 'POST',
              success(res) {
                var res = res.data;
                console.log(res);
                if (res.status == 1) {
                  wx.setStorage({
                    key: 'token',
                    data: res.data.session_key
                  });
                  wx.setStorage({
                    key: 'openid',
                    data: res.data.openid
                  });
                  wx.setStorageSync("session_key", res.data.session_key);//存到缓存里面openid
                  wx.setStorageSync("openid", res.data.openid);//存到缓存里面openid

                } else {
                  wx.showToast({
                    title: res.msg,
                    icon: 'none',
                    duration: 2000
                  })
                }

              }
            })


      
          }
        })


      },
      fail: function() {
          wx.showModal({
              title: "获取信息失败",
              content: "请允许授权以便为您提供给服务",
              success: function(e) {
                  e.confirm && this.getUserProfile();
              }
          });
      }
    })
  },
  getUserInfo(e) {
    // 不推荐使用getUserInfo获取用户信息，预计自2021年4月13日起，getUserInfo将不再弹出弹窗，并直接返回匿名的用户个人信息
    console.log(e)
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  downImg(e){
    console.log(1);
    var self = this;
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope:'scope.writePhotosAlbum',
            success() {
              wx.saveImageToPhotosAlbum({
                filePath: self.data.imagePath,
                success: function (data) {
                  wx.showToast({
                    title: '保存成功',
                    icon: 'success',
                    duration: 2000
                  })
                }
              })
            },
            fail() {
              wx.showModal({
                title: "qing信息失败",
                content: "请允许授权以便为您提供给服务",
                success: function(e) {
                    e.confirm && this.getUserProfile();
                  }
              });
            },
          })
        }else{
          wx.saveImageToPhotosAlbum({
                filePath: self.data.imagePath,
                success: function (data) {
                  wx.showToast({
                    title: '保存成功',
                    icon: 'success',
                    duration: 2000
                  })
                }
              })
        }
      }
    })
  },
  onShareAppMessage: function () {
    var that = this;
    return {
      title: '和善龙江',
      path:'/pages/index/index',
       imageUrl: 'http://cdn2.kyhdmedia.com/xcx_ljcs/share.jpg'
    }
  },
  onShareTimeline: function () {
    var that = this;
    return {
      title: '和善龙江',
      path:'/pages/index/index',
       imageUrl: 'http://cdn2.kyhdmedia.com/xcx_ljcs/share.jpg'
    }
  }
})
